/**
* @file SatListReader.cpp
* Class to handle interpolatable time serial data
*/

//============================================================================
//
//  Shoujian Zhang, Wuhan University, 2013
//
//============================================================================

#include "StringUtils.hpp"
#include "SatListReader.hpp"
#include "MiscMath.hpp"
#include "CommonTime.hpp"
#include "MJD.hpp"
#include <fstream>

using namespace std;
using namespace gpstk::StringUtils;

#define debug 0

namespace gpstk
{

   void SatListReader::loadFile(std::string file)
      noexcept(false)
   {


      ifstream inpf(file.c_str());
      if(!inpf)
      {
         FileMissingException fme("Could not open leap second file " + file);
         GPSTK_THROW(fme);
      }

      clear();

         // first we skip the header section
         // skip the header with note "#"
         // --->
         // # ...
         // # ...
         // <---
         //
         // Now, read the leap second data
      bool ok (true);
      while(!inpf.eof() && inpf.good())
      {
         string line;
         getline(inpf,line);
         StringUtils::stripTrailing(line,'\r');

         if(inpf.eof()) break;

         if(debug)
         {
            cout << "line:" << line << endl;
         }

            // line length is actually 185
         if( inpf.bad() )
         { 
             ok = false; 
             break; 
         }

         if(line.size() != 0)
         {
             SatID sat;

             string sys( line.substr(0,1) );
             int id( asInt(line.substr(1,2)) );

             if(sys == "G")
             {
                 sat = SatID(id, SatelliteSystem::GPS);
             }
             else
             {
                 continue;
             }

             if(debug) cout << sat << endl;

             satSet.insert(sat);
         }
      }

      inpf.close();

      if(!ok)
      {
         FileMissingException fme("LeapSec File " + file
                                  + " is corrupted or wrong format");
         GPSTK_THROW(fme);
      }
   }


   SatIDSet SatListReader::getSatSet() const
      noexcept(false)
   {
       return satSet;

   }  // End of method 'SatListReader::getLeapSec()'


}  // End of namespace gpstk
